<?php
/**
 * Created by 团购类.
 * User: 尚金殿
 * Date: 2018/8/29
 * Time: 16:51
 */

namespace app\app\controller\v1;


use app\app\util\OnlineUtils;
use think\Db;
use think\Request;

class CollageController extends BaseController
{

    //团购列表
    public function collageListsByUserId(){
        //获取用户ID
        $user_id = OnlineUtils::getUserIdBySid();

        if(!$user_id || !is_numeric($user_id)){
            return show(0,'用户ID不能为空');
        }

        //获取状态
        $status = $this->request->param('status');
        if($status == false){
            //查询当前用户的全部团购信息
            $member = Db::name('collage')->alias('c')->join('t_collage_member m', 'c.collage_id = m.collage_id')->join('t_line l', 'c.ware_id = l.id')->where(['m.user_id' => $user_id])->field('m.member_code,l.title,l.cover,c.collage_price,l.price,m.member_status,c.collage_status,c.collage_num,m.collage_id,m.member_id')->paginate(5);
        }else {
            //查询团购成员表
            $member = Db::name('collage')->alias('c')->join('t_collage_member m', 'c.collage_id = m.collage_id')->join('t_line l', 'c.ware_id = l.id')->where('c.collage_status =' . $status)->where(['m.user_id' => $user_id])->field('m.member_code,l.title,l.cover,c.collage_price,l.price,m.member_status,c.collage_status,c.collage_num,m.collage_id,m.member_id')->paginate(5);
        }
        //获取该团购参团人数

        $collageLists = array();
        foreach($member as $k => $v){
            $v['people'] = Db::name('collage_member')->where('collage_id',$v['collage_id'])->count();
            $collageLists[] = $v;
        }

        if(!$collageLists){
            return show(0,'没有参团数据');
        }
        return show(1,'OK',$collageLists);
    }









    //创建团购
    public function addCollage(Request $request){
        //获取用户ID
        $user_id = OnlineUtils::getUserIdBySid();;

        if(!$user_id || !is_numeric($user_id)){
            return show(0,'用户ID不能为空');
        }
        //获取团购信息
        $data = $request->param();

        //验证数据
        $result = self::collageValidate($data);

        //判断当前用户是否创建过该商品的拼团


        //获取商品信息
        $ware = Db::name('line')->where('id',$result['ware_id'])->find();

        if($ware['ware_type_id'] != 3){
            return show(0,'该商品不是拼团商品');
        }

        //拼接(拼团)数据
        $res['collage_code'] = OnlyOneOrderNumber();
        $res['create_time'] = $res['update_time'] = time();
        $res['collage_status'] = 1;
        $res['ware_id'] = $result['ware_id'];
        $res['collage_num'] = $ware['collage_people'];
        $res['collage_price'] = $ware['collage_price'];
        $res['collage_time'] = $ware['collage_time'];

        //拼团订单入库
        $collageId = Db::name('collage')->insertGetId($res);

        if(!$collageId){
            return show(0,'拼团订单失败');
        }

        //拼接(拼团人员)数据
        $member = array(
            'user_id' => $user_id,
            'collage_id' => $collageId,
            'is_colonel' => 1,
            'create_time' => time(),
            'update_time' => time(),
            'member_status' => 0,
            'name' => $result['name'],
            'phone' => $result['phone'],
            'id_card' => $result['id_card'],
            'member_code' => OnlyOneOrderNumber(),
        );

        //拼团人员入库
        $memberId = Db::name('collage_member')->insertGetId($member);

        if(!$memberId){
            return show(0,'拼团人员失败');
        }
            return show(1,'拼团成功',['memberId'=>$memberId,'collageId'=>$collageId]);
    }



    //拼团详情
    public function collageInfoByCollageId(){
        //获取拼团ID
        $collageId = $this->request->param('id');

        //获取拼团订单表
        $collage = Db::name('collage')->where('collage_id',$collageId)->field('collage_id,ware_id,create_time,collage_time,collage_num')->find();
        //获取商品信息
        $collage['ware'] = Db::name('line')->where('id',$collage['ware_id'])->field('title,remarks,price,collage_price,cover')->find();
        //获取拼团成员
        $collage['user'] = Db::name('collage_member')->alias('m')->join('t_user u','m.user_id=u.id')->where('m.collage_id',$collageId)->field('u.avatar_url,m.is_colonel,m.user_id')->select();
        //获取拼团成员人数
        $count = Db::name('collage_member')->where('collage_id',$collageId)->count();

        //已参团人员ID
        $collage['people'] = array();
        foreach($collage['user'] as $k => $v){
            $collage['people'][] = $v['user_id'];
        }
        $collage['end_time'] = $collage['create_time'] + $collage['collage_time'] * 60 * 60;
        //判定拼团
        if(time() >= $collage['end_time']){
            return show(0,'时间过期',$collage);
        }else if($count >= $collage['collage_num']){
            return show(2,'拼团已完成',$collage);
        }else{
            return show(1,'可以拼团',$collage);
        }

    }




    //支付团购
    public function toPayCollage(Request $request){
        //获取用户ID
        $user_id = OnlineUtils::getUserIdBySid();;

        //获取团员ID
        $memberId = $request->param('id');
		
        //判定用户ID是否跟传递的拼团人员ID一致(并获取用户openId和信息)
        $collage = self::validateCollageInfoOrUserInfo($user_id,$memberId);

        //获取商品信息
        $ware = self::getWareInfoByCollageId($collage['ware_id']);

        //微信支付
        $data_pay_sign = self::splicingData($ware,$collage);

        echo json_encode($data_pay_sign);


    }



    //支付回调
    public function collageCallBack(){
        //获取微信回调
        $res = file_get_contents('php://input');
        //转化xml数据
        $res = simplexml_load_string($res,'SimpleXMLElement',LIBXML_NOCDATA);

        //获取商户号
        $mch_id = $res->mch_id;
        //获取用户openid
        $openid = $res->openid;
        //获取自己的订单号
        $out_trade_no = $res->out_trade_no;
        //获取返回业务结果
        $result_code = $res->result_code;
        $return_code = $res->return_code;
        //获取支付金额
        $total_fee = $res->total_fee;


        //获取自己的商户号
        $wechat = config('WeChat');

        $res = self::getCollageInfoOrUserInfoOrWareInfoByCollageCode($out_trade_no);

        //判定微信是否扣款成功
        if($result_code == 'SUCCESS' && $return_code == 'SUCCESS'){
            //判定商户号    判定用户    判定金额
            if($mch_id == $wechat['MCH_ID']  || $openid == $res['open_id'] || ($total_fee / 100) == $res['collage_price']){
                //入库修改数据
                $data = array(
                    'member_status' => 1,
                    'update_time' => time(),
                );
                //修改拼团人员数据
                $res = Db::name('collage_member')->where('member_id',$res['member_id'])->update($data);

                //查询拼团是否成功
                $collage = Db::name('collage')->where('collage_id',$res['collage_id'])->find();
                $ware = Db::name('line')->where('id',$collage['ware_id'])->find();
                //查询拼团人数
                $collageProPleCount = Db::name('collage_member')->where('collage_id',$res['collage'])->count();

                if($ware['collage_people'] == $collageProPleCount){
                    $result = array(
                        'collage_status' => 2,
                        'update_time' => time(),
                    );

                    $res = Db::name('collage')->where('collage_id',$res['collage_id'])->update($result);
                }

                if($res){
                    return '<xml>
                                <return_code><![CDATA[SUCCESS]]></return_code>
                                <return_msg><![CDATA[OK]]></return_msg>
                                </xml>';
                }

            }
        }
    }


    //邀请好友拼团
    public function addInviteFriends(){
        //获取好友id
        $user_id = OnlyOneOrderNumber();

        //获取拼团ID
        $data['collage_id'] = $this->request->param('id');
        $data['name'] = $this->request->param('name');   //出发人
        $data['phone'] = $this->request->param('phone'); //手机号
        $data['id_card'] = $this->request->param('idcard'); //身份证号


        //查询拼团是否可以满团或者时间是否过期
        $collage = Db::name('collage')->where('collage_id',$data['collage_id'])->find();

        //获取拼团成员总数
        $count = Db::name('collage_member')->where('collage_id',$data['collage_id'])->count();

        if($count >= $collage['collage_num'] || time() > $collage['create_time'] + $collage['collage_time'] * 60 * 60){
            return show(0,'拼团满员或时间已过期');
        }

        //拼接数据
        $data['create_time'] = $data['update_time'] = time();
        $data['member_code'] = OnlyOneOrderNumber();
        $data['member_status'] = 0;

        //入库
        $memberId = Db::name('collage_member')->insertGetId($data);

        if(!$memberId){
            return show(0,'入团失败');
        }
            return show(1,'入团成功',['memberId'=>$memberId]);

    }


    //团购信息验证
    public static function collageValidate($arr){
        if(!$arr || !is_array($arr)){
            return show(0,'空数据');
        }

        //获取商品ID
        $data['ware_id'] = $arr['id'];
        if(!$data['ware_id'] || !is_numeric($data['ware_id'])){
            return show(0,'商品ID不能为空');
        }

        //获取出发人
        $data['name'] = $arr['name'];
        if(!$data['name']){
            return show(0,'出发人不能为空');
        }
        //获取手机号
        $data['phone'] = $arr['phone'];
        if(!$data['phone']){
            return show(0,'手机号不能为空');
        }
        //获取身份证号
        $data['id_card'] = $arr['idcard'];

        return $data;

    }



    //判定团购数据和用户数据(返回用户openid和团购信息)
    public static function validateCollageInfoOrUserInfo($userId,$memberId){

        //判定用户ID
        if(!$userId || !is_numeric($userId)){
            return show(0,'用户ID不能为空');
        }
        //判定团购表ID
        if(!$memberId || !is_numeric($memberId)){
            return show(0,'团购ID不能为空');
        }

        //查询拼团人员表
        $member = Db::name('collage_member')->where('member_id',$memberId)->find();

        //判定拼团人员表
        if(!$member || !is_array($member)){
            return show(0,'空数据');
        }
        //判定用户ID是否跟拼团人员一致
        if($userId != $member['user_id']){
            return show(0,'用户ID不一致');
        }

        //获取用户openid
        $user = Db::name('user')->where('id',$userId)->find();
        //获取拼团订单表
        $collage = Db::name('collage')->where('collage_id',$member['collage_id'])->find();

        $collage['openid'] = $user['open_id'];
        $collage['member_code'] = $member['member_code'];

        return $collage;
    }

    //获取商品信息
    public static function getWareInfoByCollageId($wareId){
        //判定团购表ID
        if(!$wareId || !is_numeric($wareId)){
            return show(0,'商品ID不能为空');
        }

        $ware = Db::name('line')->where('id',$wareId)->find();

        if($ware['ware_type_id'] == 3){
            return $ware;
        }
        return show(0,'该商品不是团购商品');
    }

    //获取拼团信息
    public static function getCollageInfoByCollageId($id){

        $collage = Db::name('collage')->where('collage_id',$id)->find();

        //判定团购表数据
        if(!$collage || !is_array($collage)){
            return show(0,'空数据');
        }

        return $collage;
    }

    //微信支付
    public static function splicingData($ware,$collage){
        $nonce_str = md5(rand(1000,9999999));//随机字符串

        $APPID = config('MCH_APPID');
        $MCH_ID = config('MCH_ID');
        $KEY = config('WX_APP_KEY');

        //拼接数组
        $data_sign = array(
            'appid' =>$APPID,
            'mch_id' => $MCH_ID,     //商户号
            'nonce_str' => $nonce_str,
            'body' => $ware['title'],    //商品名称
            'out_trade_no'=>$collage['member_code'],    //订单号
            'total_fee' => $collage['collage_price'] * 100,    //商品总价
            'spbill_create_ip' => Request::instance()->ip(),    //支付Ip
            'notify_url' => 'https://'.$_SERVER['HTTP_HOST'].'/collageCallBack',   //支付回调
            'trade_type' => 'JSAPI',
            'openid' => $collage['openid']   //用户openid
        );

        //签名
        $sign = self::sign($data_sign,$KEY);

        //拼接xml数据
        $xml_data = '<xml>
                        <appid>'.$data_sign['appid'].'</appid>
                        <mch_id>'.$data_sign['mch_id'].'</mch_id>
                        <nonce_str>'.$data_sign['nonce_str'].'</nonce_str>
                        <body>'.$data_sign['body'].'</body>
                        <out_trade_no>'.$data_sign['out_trade_no'].'</out_trade_no>
                        <total_fee>'.$data_sign['total_fee'].'</total_fee>
                        <spbill_create_ip>'.$data_sign['spbill_create_ip'].'</spbill_create_ip>
                        <notify_url>'.$data_sign['notify_url'].'</notify_url>
                        <trade_type>JSAPI</trade_type>
                        <openid>'.$data_sign['openid'].'</openid>
                        <sign>'.$sign.'</sign>
                    </xml>';

        //发送请求(调用统一下单)
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $ret_pay = self::Curl($url,$xml_data);
        file_put_contents('a.php',$ret_pay);
        //获取预下单ID
        $payId = self::getPreId($ret_pay);
        $pre_pay_id = 'prepay_id='.$payId;

        //拼接返回数据
        $data_pay_sign = array(
            'appId' => $APPID,
            'timeStamp' => "'".time()."'",
            'nonceStr' => md5(rand(1000,99999999)),
            'package' => $pre_pay_id,
            'signType' => 'MD5',
        );

        //再次签名
        $pay_sign = self::sign($data_pay_sign,$KEY);

        //删除appid
        unset($data_pay_sign['appId']);

        $data_pay_sign['paySign'] = $pay_sign;

        return $data_pay_sign;

    }

    //签名
    public static function sign($data,$key){
        ksort($data);

        $str = '';

        foreach($data as $k => $v){
            $str.=$k.'='.$v.'&';
        }

        $str.='key='.$key;

        return strtoupper(md5($str));
    }

    //获取预下单ID
    public static function getPreId($xml){
        $res = simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA);
        return $res->prepay_id;
    }

    //获取团购信息 用户信息 商品信息
    public static function getCollageInfoOrUserInfoOrWareInfoByCollageCode($code){
        //获取拼团信息
        $member = Db::name('collage_member')->where('member_code',$code)->find();

        if(!$member || !is_array($member)){
            return show(0,'拼团人员数据获取错误');
        }
        //获取openid
        $user = Db::name('user')->where('id',$member['user_id'])->find();
        if(!$user || !is_array($user)){
            return show(0,'用户数据获取错误');
        }

        //获取拼团订单表
        $collage = Db::name('collage')->where('collage_id',$member['collage_id'])->find();
        if(!$collage || !is_array($collage)){
            return show(0,'拼团订单数据获取错误');
        }



        $result = array(
            'member_id' => $collage['member_id'],
            'open_id' => $user['open_id'],
            'collage_price' => $collage['collage_price'],
            'collage_id' => $collage['collage_id']
        );

        return $result;
    }

//定时任务
    public function timedTask(){
        //获取全部团购信息
        $collages = Db::name('collage')->where('collage_status','eq',1)->select();

        //循环
        foreach($collages as $key => $value){
            //判定时间是否过期
            if(time() == $value['create_time'] + $value['collage_time'] * 60 * 60 || time() > $value['create_time'] + $value['collage_time'] * 60 * 60){
                //判定团员人数
                $count = Db::name('collage_member')->where('collage_id',$value['collage_id'])->where('member_status',1)->count();
                if($count < $value['collage_num']){
                    //团员人数小余拼团总人数(修改拼团状态【失败】)
                    $data['collage_status'] = 2;
                    $data['update_time'] = time();
                    $res = Db::name('collage')->where('collage_id',$value['collage_id'])->update($data);
                    //判定是否修改成功
                    if(!$res){
                        file_put_contents('error.php',$res);
                    }
                    //退款
                    $result = $this->refund($value['collage_id']);
                    if(!$result){
                        file_put_contents('error.php',$result);
                    }
                }else if($count == $value['collage_num']){
                    //团员人数等于拼团总人数(修改拼团状态【成功】)
                    $data['collage_status'] = 3;
                    $data['update_time'] = time();
                    Db::name('collage')->where('collage_id',$value['collage_id'])->update($data);
                }
            }
        }
    }

    //退款到余额
    public function refund($collage_id){
        //判定拼团订单ID
        if(!$collage_id || !is_numeric($collage_id)){
            return show(0,'拼团订单ID为空');
        }
        //获取拼团订单的信息
        $collage = Db::name('collage')->where('collage_id',$collage_id)->find();

        //根据拼团订单ID查询出团员信息
        $members = Db::name('collage_member')->where('collage_id',$collage_id)->select();

        $refundId = '';

        //循环退款
        foreach($members as $k => $v){
            //如果团员没有付款的话就不用退款了
            if($v['member_status'] == 1){
                //获取用户信息
                $user = Db::name('user')->where('id',$v['user_id'])->find();
                //获取金额
                $data['balance'] = $user['balance'] + $collage['collage_price'];
                //修改用户余额
                $res = Db::name('user')->where('id',$v['user_id'])->update($data);
                if(!$res){
                    return show(0,'用户余额修改失败');
                }
                //修改团员状态(已退款)
                $arr['member_status'] = 2;
                $arr['update_time'] = time();
                $str = Db::name('collage_member')->where('member_id',$v['member_id'])->update($arr);
                if(!$str){
                    return show(0,'团员状态修改失败');
                }
                //成功的话就添加数据到退款表中
                $result = array(
                    'user_id' => $v['user_id'],
                    'refund_price' => $collage['collage_price'],
                    'collage_id' => $v['collage_id'],
                    'refund_status' => 1,
                    'create_time' => time(),
                    'member_id' => $v['member_id']
                );
                $refundId = Db::name('collage_refund')->insertGetId($result);
            }
        }

        return $refundId;
    }

}